//
//  PALoginVC.m
//  PilotSeries
//
//  Created by 黄立强 on 16/6/29.
//  Copyright © 2016年 leon.huang. All rights reserved.
//

#import "PALoginVC.h"
#import "PATextField.h"
#import "PAAccountManager.h"
#import "PAUser.h"
#import <PgyUpdate/PgyUpdateManager.h>
#import "HttpManager.h"
#import "PAChartConfigManager.h"
#import "ChartConfig.h"



@interface PALoginVC ()<PAWebSocketManagerRangeListDelegete,PAWebSocketManagerFirstOpenDelegete,PAWebSocketManagerChartConfigListDelegete>
@property (weak, nonatomic) IBOutlet PATextField *usernameText;
@property (weak, nonatomic) IBOutlet PATextField *passwordText;
@property (weak, nonatomic) IBOutlet UISegmentedControl *envSegment;
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@end

@implementation PALoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpEnvironment];
    [self setUpDelegate];
    
//     NSURL *ndexURL = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html" subdirectory:@"Resource/default_app"];
//
//    NSData *data = [NSData dataWithContentsOfURL:ndexURL];
//    LOG(@"ndexURL:%@",data);
}

-(void)viewDidAppear:(BOOL)animated{
    //    [[PgyUpdateManager sharedPgyManager] checkUpdate];
    [[PgyUpdateManager sharedPgyManager] checkUpdateWithDelegete:self selector:@selector(updateMethod:)];
   
}
-(void)setUpEnvironment{
    
    PAUser *pauser = [PAAccountManager currentPAUser];
    self.envSegment.selectedSegmentIndex = pauser.env;
    self.usernameText.text = pauser.username;
    self.passwordText.text = pauser.password;
    [PAAppContext sharedInstance].envType = self.envSegment.selectedSegmentIndex;
    [self.envSegment addTarget:self action:@selector(radioValueChangedEvent:) forControlEvents:UIControlEventValueChanged];
    [self.loginBtn addTarget:self action:@selector(login:) forControlEvents:UIControlEventTouchUpInside];
    
}

- (BOOL)validateform {
    if ([self.usernameText.text isEqualToString:@""] ) {
        
        [self.usernameText shake];
        return  NO;
    }
    if ([self.passwordText.text isEqualToString:@""] ) {
        
        [self.passwordText shake];
        return  NO;
    }
    return YES;
}

- (void)login:(id)sender {
    
    if (![self validateform]) {
        return;
    };
    
    [self.view endEditing:YES];
    
    
    [self loginToServer];
    
    
}

-(void)loginToServer{
    [SVProgressHUD showWithStatus:@"login.."];
    LOG(@"loginUrl:%@",[PAAppContext sharedInstance].chartingview_login_url)
    [HttpManager sslPost:[PAAppContext sharedInstance].chartingview_login_url params:@{LQLoginUsernameKey_Jahan:self.usernameText.text,LQLoginPasswordKey:self.passwordText.text,LQLoginAuthnTypeKey:LQLoginAuthnTypeValue,@"captcgaRequired":@NO} success:^(id responseObj) {
         NSString *token = responseObj[@"ASSERTION"];
        //保存当前用户信息并插入到数据库
        PAUser *user = [PAUser new];
        user.username = self.usernameText.text.uppercaseString;
        user.password = self.passwordText.text;
        user.env = self.envSegment.selectedSegmentIndex;
        
        [PAAccountManager saveCurrentPAUser:user];
        [PAAccountManager saveUser:user];
        [PAAppContext sharedInstance].token =[token urlEncode];
        [PAAppContext sharedInstance].username = self.usernameText.text.uppercaseString;
        
        NSUserDefaults *userdefault =  [NSUserDefaults standardUserDefaults];
        [userdefault setObject:[NSString stringWithFormat:@"%@@pingan.com.cn",user.username] forKey:@"PGY_EMAIL_ADRESS"];
        [userdefault synchronize];
        
        NSString *url = [NSString stringWithFormat:@"ws://%@:%lu?token=%@",[PAAppContext sharedInstance].w_host,(unsigned long)[PAAppContext sharedInstance].w_port,[PAAppContext sharedInstance].token];
        [[PAWebSocketManager sharedInstance] connectToWebSocketServer:url];
        
    } failure:^(NSInteger code,NSError *error) {
        
        [SVProgressHUD dismiss];
        if (code == 500) {
            [CRToastManager showNotificationWithMessage:Error_Htttp_500_MSG completionBlock:^{
                
            }];
          
        }else if(code == 403){
            [CRToastManager showNotificationWithMessage:Error_Htttp_403_MSG completionBlock:^{
                
            }];
        }else if (code == 401){
            [CRToastManager showNotificationWithMessage:Error_Htttp_401_MSG completionBlock:^{
                
            }];
            
        }else if (code== 407){
            [CRToastManager showNotificationWithMessage:Error_Htttp_407_MSG completionBlock:^{
                
            }];
            
        }else{
            [CRToastManager showNotificationWithMessage:Error_Htttp_Other_MSG completionBlock:^{
                
            }];
        }
         LOG(@"login failure")
    }];
    
  
    
}
-(void)setUpDelegate{
    [PAAppContext sharedInstance].rangelistDelegete = self;
    [PAAppContext sharedInstance].chartConfiglistDelegete = self;
    [PAWebSocketManager sharedInstance].firstOpenDelegate = self;
    
}

- (void)radioValueChangedEvent:(UISegmentedControl *)sender {
    [PAAppContext sharedInstance].envType = self.envSegment.selectedSegmentIndex;
}

/**
 *  检查更新回调
 *
 *  @param response 检查更新的返回结果
 */
- (void)updateMethod:(NSDictionary *)response
{
    if (response[@"downloadURL"]) {
        
        NSString *message = response[@"releaseNote"];
        
        [UIAlertView alertWithCallBackBlock:^(NSInteger buttonIndex) {
            if (buttonIndex==1) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:response[@"downloadURL"]]];
//                [[PgyUpdateManager sharedPgyManager] updateLocalBuildNumber];
            }
            
        } title:@"New version for PilotSeries" message:message cancelButtonName:@"cancel" otherButtonTitles:@"install", nil];
        
        
    }
    
}
/**
 *  收到rangelist后
 *
 *  @param rangeList rangeList description
 */
-(void)webSocketManagerDidReiceveRangeList:(NSArray *)rangeList{

    //发送configchartList指令
    [self sendConfigChartLists];
    
}

/**
 *  websocket第一次打开
 *
 *  @param manager manager description
 */
-(void)webSocketManagerFirstOpen:(PAWebSocketManager *)manager{
    
    //    [SVProgressHUD dismiss];
    
    //发送conifg指令
    //    [self sendConfigs];
    //发送rangelist指令
//    [self sendRangeLists];
    [self sendConfigChartLists];
    [self sendMetaDataCommand];
    
    
}

-(void)sendRangeLists{
    NSDictionary *dic = @{@"command":@"rangelist",@"type":@"command",@"appid":[PAAppContext sharedInstance].appid};
    //发请求
    if(![[PAWebSocketManager sharedInstance] sendMsg:dic.mj_JSONString]) return;
}

-(void)sendConfigs{
//    NSArray *configs = [PAChartConfigManager loadCurrentChartConfigs];
//    if (configs.count>0) {
//        [configs enumerateObjectsUsingBlock:^(ChartConfig  *chartConfig, NSUInteger idx, BOOL * _Nonnull stop) {
//             NSDictionary *config = chartConfig.config;
//            [[PAWebSocketManager sharedInstance] sendMsg:config.mj_JSONString];
//
//        }];
//    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
          [self goTOMainPage];
    });
  
    
}

-(void) sendMetaDataCommand{
    NSDictionary *dic = @{@"command":@"metadata",@"type":@"command",@"appid":[PAAppContext sharedInstance].appid};
    //发请求
    if(![[PAWebSocketManager sharedInstance] sendMsg:dic.mj_JSONString]) return;
}

-(void)sendConfigChartLists{
    
    NSDictionary *dic = @{@"command":@"chartConfigList",@"type":@"command",@"appid":[PAAppContext sharedInstance].appid};
    //发请求
    [[PAWebSocketManager sharedInstance] sendMsg:[dic mj_JSONString]];
}

-(void)webSocketManagerDidReiceveChartConfigList:(NSArray *)chartConfigList{
    [self sendConfigs];
    
}

-(void)goTOMainPage{
    [SVProgressHUD dismiss];
    UIStoryboard *story  = [UIStoryboard storyboardWithName:@"Split" bundle:[NSBundle mainBundle]];
    PASplitVC *spVC = [story instantiateViewControllerWithIdentifier:@"splitVC"];
    
    [UIApplication sharedApplication].keyWindow.rootViewController = spVC;
    
}
@end
